package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zx
 * @date 2021/11/26 19:59
 */
@Service
@Slf4j
public class ApUserLoginServiceImpl  implements ApUserLoginService {


    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        log.info("用户登录");

        //1.校验参数
        if(dto.getEquipmentId() == null){

            log.error("设备id为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2 查询登录用户
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {

            //2.1 检验用户是否存在
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getStatus, 0).eq(ApUser::getPhone, dto.getPhone()));

            //2.1.1 用户手机号检验
            if (apUser == null) {
                log.error("用户手机号或者密码错误");
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "请检查手机号");
            }

            // 2.2.2用户密码检验
            String PWD = apUser.getPassword();//数据库中的密码
            String inPWD = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes()); //用户输入的，加盐后的密码
            if (!inPWD.equals(PWD)) {
                log.error("用户密码错误");
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号或密码错误");
            }

            //3 封装
            Map<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user", apUser);

            //返回
            log.info("用户登录成功");
            System.out.println("用户登录成功");

            return ResponseResult.okResult(map);
        }else {
            log.info("游客登录");

            Map<String,Object> map = new HashMap<>();

            // 通过设备ID登录的 userId存0
            map.put("token",AppJwtUtil.getToken(0L));
            log.info("游客登录成功");

            System.out.println("游客登录成功");
            return ResponseResult.okResult(map);
        }
    }
}
